package com.shigen.springcloud.controller;

import com.shigen.lb.LoadBalancer;
import com.shigen.springcloud.entity.CommonResult;
import com.shigen.springcloud.entity.Payment;
import java.net.URI;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping(value = "payment/consumer")
public class OrderController {

  @Resource
  private RestTemplate restTemplate;

  @Resource
  private DiscoveryClient discoveryClient;

  @Resource
  private LoadBalancer loadBalancer;

  // public static final String PAYMENT_URL = "http://127.0.0.1:8001";
  public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

  @PostMapping(value = "create")
  public CommonResult create(@RequestBody Payment payment) {
    return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
  }

  @GetMapping(value = "getPayment/{id}")
  public CommonResult getPaymentByid(@PathVariable("id") Long id) {
    return restTemplate.getForObject(PAYMENT_URL + "/payment/getPayment/" + id, CommonResult.class);
  }

  @GetMapping(value = "getForEntity/{id}")
  public CommonResult getForEntity(@PathVariable("id") Long id) {
    ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/getPayment/" + id, CommonResult.class);
    System.out.println(entity);
    if (entity.getStatusCode().is2xxSuccessful()) {
      return entity.getBody();
    }
    return new CommonResult(444, "不存在");
  }

  @GetMapping(value = "lb")
  public String getPaymentLB() {
    List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
    if (CollectionUtils.isEmpty(instances)) {
      return null;
    }
    ServiceInstance instance = loadBalancer.instances(instances);
    URI uri = instance.getUri();
    return restTemplate.getForObject(uri + "payment/lb", String.class);
  }
}
